package com.zy.datareceiver.core.utils;

import com.alibaba.fastjson.JSONObject;
import com.zy.datareceiver.binsess.monitoring.param.index.Weather;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;

/**
 * java调用中央气象局天气预报接口
 *
 * @author RoninGirl
 *
 */
public class WeatherUtil {
    private static final Logger log = LoggerFactory.getLogger(WeatherUtil.class);

    private volatile static AtomicLong time = new AtomicLong(0);
    private volatile static Weather weatherinfo = new Weather();
    private static final Long SPLIT=1000 * 60 * 5L;

    /**
     * 获取一周天气<br>
     * 方 法 名：getWeekWeatherMap <br>
     * @param Cityid  城市编码
     */
    public static List<Map<String, String>> getWeekWeatherMap(String Cityid)
            throws IOException, NullPointerException {
        // 连接中央气象台的API
        URL url = new URL("http://m.weather.com.cn/data/" + Cityid + ".html");
        URLConnection connectionData = url.openConnection();
        connectionData.setConnectTimeout(1000);
        // 得到1到6天的天气情况
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        BufferedReader br = null;
        InputStreamReader in = null;
        try {
            in = new InputStreamReader(connectionData.getInputStream(), "UTF-8");
            br = new BufferedReader(in);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null)
                sb.append(line);
            String datas = sb.toString();

            JSONObject jsonData = JSONObject.parseObject(datas);
            JSONObject info = jsonData.getJSONObject("weatherinfo");
            for (int i = 1; i <= 6; i++) {
                // 得到未来6天的日期
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.DAY_OF_YEAR, i - 1);
                Date date = cal.getTime();
                SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日");
                Map<String, String> map = new HashMap<String, String>();
                map.put("city", info.getString("city").toString());// 城市
                map.put("date_y", sf.format(date));// 日期
                map.put("week", getWeek(cal.get(Calendar.DAY_OF_WEEK)));// 星期
                map.put("fchh", info.getString("fchh").toString());// 发布时间
                map.put("weather", info.getString("weather" + i).toString());// 天气
                map.put("temp", info.getString("temp" + i).toString());// 温度
                map.put("wind", info.getString("wind" + i).toString());// 风况
                map.put("fl", info.getString("fl" + i).toString());// 风速
                // map.put("index", info.getString("index").toString());//
                // 今天的穿衣指数
                // map.put("index_uv", info.getString("index_uv").toString());//
                // 紫外指数
                // map.put("index_tr", info.getString("index_tr").toString());//
                // 旅游指数
                // map.put("index_co", info.getString("index_co").toString());//
                // 舒适指数
                // map.put("index_cl", info.getString("index_cl").toString());//
                // 晨练指数
                // map.put("index_xc", info.getString("index_xc").toString());//
                // 洗车指数
                // map.put("index_d", info.getString("index_d").toString());//
                // 天气详细穿衣指数
                list.add(map);
            }
        } catch (SocketTimeoutException e) {
            System.out.println("连接超时");
        } catch (FileNotFoundException e) {
            System.out.println("加载文件出错");
        }finally {
            if (in != null){
                try {
                    in.close();
                }catch (IOException e){
                    log.error("input stream colse error {}",e);
                }
            }
            if (br != null){
                try {
                    br.close();
                }catch (IOException e){
                    log.error("buffer stream colse error {}",e);
                }
            }

        }

        return list;

    }

    /**
     *
     * 获取实时天气1<br>
     * 方 法 名： getTodayWeather <br>
     *
     * @param Cityid
     *            城市编码
     */
    public static Map<String, String> getTodayWeather1(String Cityid)
            throws IOException, NullPointerException {
        // 连接中央气象台的API
        URL url = new URL("http://www.weather.com.cn/data/sk/" + Cityid
                + ".html");
        URLConnection connectionData = url.openConnection();
        connectionData.setConnectTimeout(1000);
        Map<String, String> map = new HashMap<String, String>();

        BufferedReader br = null;
        InputStreamReader in = null;
        try {
            in = new InputStreamReader(connectionData.getInputStream(), "UTF-8");
            br = new BufferedReader(in);

            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null)
                sb.append(line);
            String datas = sb.toString();

            JSONObject jsonData = JSONObject.parseObject(datas);
            JSONObject info = jsonData.getJSONObject("weatherinfo");
            Set<String> keys = info.keySet();
            for (String key:keys) {
                map.put(key,info.getString(key).toString());
            }
        } catch (SocketTimeoutException e) {
            System.out.println("连接超时");
        } catch (FileNotFoundException e) {
            System.out.println("加载文件出错");
        }finally {
            if (in != null){
                try {
                    in.close();
                }catch (IOException e){
                    log.error("input stream colse error {}",e);
                }
            }
            if (br != null){
                try {
                    br.close();
                }catch (IOException e){
                    log.error("buffer stream colse error {}",e);
                }
            }
        }
        return map;
    }


    /**
     *
     * 获取实时天气2<br>
     * 方 法 名： getTodayWeather <br>
     *
     * @param Cityid
     *            城市编码
     */
    public static Map<String, String> getTodayWeather2(String Cityid)
            throws IOException, NullPointerException {
        // 连接中央气象台的API
        URL url = new URL("http://www.weather.com.cn/data/cityinfo/" + Cityid  + ".html");
        URLConnection connectionData = url.openConnection();
        connectionData.setConnectTimeout(1000);
        Map<String, String> map = new HashMap<String, String>();
        BufferedReader br = null;
        InputStreamReader in = null;
        try {
            in = new InputStreamReader(connectionData.getInputStream(), "UTF-8");
            br = new BufferedReader(in);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null)
                sb.append(line);
            String datas = sb.toString();

            JSONObject jsonData = JSONObject.parseObject(datas);
            JSONObject info = jsonData.getJSONObject("weatherinfo");
            Set<String> keys = info.keySet();
            for (String key:keys) {
                map.put(key,info.getString(key).toString());
            }
        } catch (SocketTimeoutException e) {
            System.out.println("连接超时");
        } catch (FileNotFoundException e) {
            System.out.println("加载文件出错");
        }finally {
            if (in != null){
                try {
                    in.close();
                }catch (IOException e){
                    log.error("input stream colse error {}",e);
                }
            }
            if (br != null){
                try {
                    br.close();
                }catch (IOException e){
                    log.error("buffer stream colse error {}",e);
                }
            }
        }

        return map;

    }

    public static Weather getWeather(String cityId){
        if (time.addAndGet(SPLIT)>System.currentTimeMillis()){
            if (weatherinfo != null){
                return weatherinfo;
            }
        }
        Map<String,String> weatherMap = new HashMap<>();
        try{
            Map<String,String> weather1 = getTodayWeather1(cityId);
            Map<String,String> weather2 = getTodayWeather2(cityId);
            weatherMap.putAll(weather1);
            weatherMap.putAll(weather2);
            weatherinfo.setCloud(weatherMap.get("WD"));
            weatherinfo.setCloudLevel(weatherMap.get("WS"));
            weatherinfo.setPressure(weatherMap.get("AP"));
            weatherinfo.setSd(weatherMap.get("SD"));
            weatherinfo.setWd(weatherMap.get("temp"));
            weatherinfo.setWeather(weatherMap.get("weather"));
            weatherinfo.setImg1(weatherMap.get("img1"));
            weatherinfo.setImg2(weatherMap.get("img2"));
        }catch (Exception e){
            log.error("get weather error {} ",e);
        }
        return weatherinfo;
    }

    private static String getWeek(int iw) {
        String weekStr = "";
        switch (iw) {
            case 1:
                weekStr = "星期天";
                break;
            case 2:
                weekStr = "星期一";
                break;
            case 3:
                weekStr = "星期二";
                break;
            case 4:
                weekStr = "星期三";
                break;
            case 5:
                weekStr = "星期四";
                break;
            case 6:
                weekStr = "星期五";
                break;
            case 7:
                weekStr = "星期六";
                break;
            default:
                break;
        }
        return weekStr;
    }

    public static void main(String[] args) {
        System.out.println(JsonUtil.obj2String(getWeather("101120201")));
    }
}